package com.liuqi.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuqi.common.base.bean.query.DynamicQuery;
import com.liuqi.common.base.service.AbstractBaseEntityService;
import com.liuqi.common.exception.AppException;
import com.liuqi.iot.bean.dto.GatewayDTO;
import com.liuqi.iot.bean.query.GatewayQuery;
import com.liuqi.iot.domain.entity.GatewayEntity;
import com.liuqi.iot.domain.mapper.GatewayMapper;
import com.liuqi.iot.service.GatewayEntityService;
import com.liuqi.sys.common.ErrorCodes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 网关服务实现 
 * @author Coder Generator 2025-03-22 15:29:27 
 **/
@Service
public class GatewayEntityEntityServiceImpl extends AbstractBaseEntityService<GatewayEntity, GatewayDTO, GatewayMapper, GatewayQuery> implements GatewayEntityService {
    @Override
    protected QueryWrapper<GatewayEntity> queryToWrapper(GatewayQuery query) {
        return this.createQueryWrapper()
                .eq(StringUtils.isNotBlank(query.getId()), "id", query.getId())
                .in(null != query.getIds(), "id", query.getIds())
                .eq(StringUtils.isNotBlank(query.getCode()), "code", query.getCode())
                .eq(StringUtils.isNotBlank(query.getName()), "name", query.getName())
                .eq(StringUtils.isNotBlank(query.getBrand()), "brand", query.getBrand())
                .eq(StringUtils.isNotBlank(query.getModel()), "model", query.getModel())
                .orderByDesc("create_time");
    }

    /**
     * 插入前处理
     * 可以执行相关参数校验，校验不通过时抛出异常
     *
     * @return false时不进行插入，true时进行插入
     */
    @Override
    protected boolean processBeforeInsert(GatewayDTO dto) {
        // 检查设备编号是否重复
        String code = dto.getCode();
        List<GatewayDTO> list = this.dynamicQuery(DynamicQuery.create()
                .eq("code", code));
        if (!list.isEmpty()) {
            throw AppException.of(ErrorCodes.IOT_GATEWAY_CODE_DUPLICATED);
        }

        return super.processBeforeInsert(dto);
    }

    /**
     * 更新前处理
     *
     * @return false时不再进行更新，true时进行更新
     */
    @Override
    protected boolean processBeforeUpdate(GatewayDTO dto) {
        String code = dto.getCode();
        if (StringUtils.isNotBlank(code)) {
            List<GatewayDTO> list = this.dynamicQuery(DynamicQuery.create().eq("code", code).neq("id", dto.getId()));
            if (!list.isEmpty()) {
                throw AppException.of(ErrorCodes.IOT_GATEWAY_CODE_DUPLICATED);
            }
        }

        return super.processBeforeUpdate(dto);
    }
}